//
//  SESubDieaseViewController.m
//  kuaiyi
//
//  Created by Stephen on 16/7/7.
//  Copyright © 2016年 Alphts. All rights reserved.
//

#import "SESubDieaseViewController.h"
#import "NSString+pinyin.h"
#import "SESearchString.h"
#import "SEDetailDiseaseDTO.h"



@interface SESubDieaseViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray <SESearchString *>*dataArray;

@property (nonatomic, strong) NSMutableArray *searchArray;

@property (nonatomic, weak) UITextField *searchField;

@property (nonatomic, assign) BOOL isSearchState;

@end

@implementation SESubDieaseViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [self loadData];

    
    //加载网络数据
    
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"identifier"];


}

-(void)setupUI{
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 200, 30)];
    
    headView.backgroundColor = [UIColor whiteColor];
    
    headView.layer.cornerRadius = 5;
    
    self.navigationItem.titleView = headView;
    
    UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, 190, 30)];
    
    searchField.delegate = self;
    
    self.searchField = searchField;
    
    searchField.placeholder = @"输入关键字";
    
    [headView addSubview:searchField];
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
}


#pragma mark - 获取网络数据
-(void)loadData{
    
    [SENetworkReachabilityTool checkNetworkWithReachableBlock:^{
        [SEDetailDiseaseDTO modelArrayWithSuccessBlock:^(NSArray<SEDetailDiseaseDTO *> *models) {
            
            for (int i = 0; i < models.count; ++i) {
                
                SESearchString *searchString = [[SESearchString alloc] init];
                
                //转拼音
                NSString *PinYin =  [models[i].ci3_name transformToPinyin];
                
                //首字母
                NSString *FirstLetter = [models[i].ci3_name transformToPinyinFirstLetter];
                
                searchString.name = models[i].ci3_name;
                searchString.namePinYin = PinYin;
                searchString.nameFirstLetter = FirstLetter;
                
                [self.dataArray addObject:searchString];
            }
            
            [SVProgressHUD dismiss];
            
            [self.tableView reloadData];
            
        } errorBlock:^{
            NSLog(@"error");
            [SVProgressHUD dismiss];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD showInfoWithStatus:@"网络连接超时"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                
            });

        }];

    }];
    
    }


#pragma mark - textField delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

-(void)textFieldDidChange:(NSNotification *)noti{
    
    UITextField *textFeild = (UITextField *)[noti object];
    
    [self startSearch:textFeild.text];
    
}


-(void)startSearch:(NSString *)string{
    
    if (self.searchArray.count > 0) {
        [self.searchArray removeAllObjects];
    }
    
    NSString *key = string.lowercaseString;
    
    NSMutableArray *temArr = [NSMutableArray array];
    
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            SESearchString *searchString = self.dataArray[idx];
            
            NSString *name = searchString.name.lowercaseString;
            NSString *namePinyin = searchString.namePinYin.lowercaseString;
            NSString *nameFirstLetter = searchString.nameFirstLetter.lowercaseString;
            
            NSRange rang1 = [name rangeOfString:key];
            
            if (rang1.length > 0) {
                [temArr addObject:searchString];
            }else{
                if ([nameFirstLetter containsString:key]) {
                    [temArr addObject:searchString];
                }else{
                    if ([nameFirstLetter containsString:[key substringToIndex:1]]) {
                        if ([namePinyin containsString:key]) {
                            [temArr addObject:searchString];
                        }
                    }
                }
            }
            
        }];
        
        [temArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (![self.searchArray containsObject:temArr[idx]]) {
                [self.searchArray addObject:temArr[idx]];
            }
        }];
        
        self.isSearchState = YES;
    }else{
        self.isSearchState = NO;
    }
    
    [self.tableView reloadData];
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([string isEqualToString:@"\n"]) {
        
        [textField resignFirstResponder];
        
        return NO;
    }
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark - Table view data source and delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (_isSearchState) {
        if (self.searchArray.count > 0) {
            return self.searchArray.count;
        }else{
            return 0;
        }
    }else{
        return self.dataArray.count;
    }
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    
    SESearchString *searchString= nil;
    
    if (_isSearchState) {
        searchString = self.searchArray[indexPath.row];
        
    }else{
        searchString = self.dataArray[indexPath.row];
    }
    
    
    cell.textLabel.text = searchString.name;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.detailDieaseBlock) {
        self.detailDieaseBlock(self.dataArray[indexPath.row].name);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark -懒加载
- (NSMutableArray *)searchArray{
    if (_searchArray == nil) {
        _searchArray = [[NSMutableArray alloc] init];
    }
    return _searchArray;
}

- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}




@end
